package view;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.LinkedList;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;

import view.actionlisteners.AddButtonActionListener;
import view.actionlisteners.SaveButtonActionListener;

// hier werden die Model Klassen importiert
import model.Address;
import model.AddressList;
import model.ISubject;
import model.IViews;

@SuppressWarnings("serial")
public class AddressListView extends JFrame implements IViews {

	private DefaultListModel listModel;

	private ISubject addressList;

	public ISubject getAddressList() {
		return addressList;
	}

	public AddressListView(ISubject addressList) {
		this.addressList = addressList;
		init();
		populateFields();
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
	}

	private void init() {
		this.addressList.registrieren(this);
		this.setTitle("Address-List");
		this.setLayout(new GridBagLayout());
		GridBagConstraints constraints = new GridBagConstraints();
		constraints.fill = GridBagConstraints.HORIZONTAL;
		constraints.gridx = 0;
		constraints.gridy = 0;
		constraints.gridwidth = 2;
		constraints.weighty = 0.9;
		listModel = new DefaultListModel();
		JList list = new JList(listModel);
		JScrollPane scrollpane = new JScrollPane(list);
		this.add(scrollpane, constraints);
		JButton addButton = new JButton("Add address");
		addButton.addActionListener(new AddButtonActionListener(this));
		constraints.weighty = 0.1;
		constraints.gridy = 1;
		constraints.gridwidth = 1;
		this.add(addButton, constraints);
		JButton saveButton = new JButton("Save all");
		saveButton.addActionListener(new SaveButtonActionListener(this));
		constraints.gridx = 1;
		constraints.gridy = 1;
		this.add(saveButton, constraints);
		this.pack();
	}

	private void populateFields() {
		refreshAddressList();
	}

	@Override
	public void update() {
		refreshAddressList();
	}

	private void refreshAddressList() {
		listModel.removeAllElements();

		for (Address address : (AddressList) addressList) {
			listModel.addElement(address.toString());
		}
	}

	public void addAddress(Address address) {
		this.addressList.addNewAdress(address);
	}
}
